using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Threading;

namespace foundation.socket
{
    public class ClientSocket
    {
        private static byte[] result = new byte[1024];
        private static readonly Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        public bool IsConnected = false;
        private Thread receiveThread = null;

        public void ConnectServer(string ip, int port)
        {
            // var mIp = IPAddress.Parse(ip);
            // var ipEndPoint = new IPEndPoint(mIp, port);

            try
            {
                clientSocket.Connect(ip, port);
                IsConnected = true;
                Debug.Log("连接服务器成功");
            }
            catch
            {
                IsConnected = false;
                Debug.Log("连接服务器失败");
                return;
            }
            //服务器下发数据长度

            receiveThread?.Abort();
            receiveThread = new Thread(ReceiveMessage);
            receiveThread.Start();

            // var receiveLength = clientSocket.Receive(result);
            // var buffer = new ByteBuffer(result);
            // int len = buffer.ReadShort();
            // var data = buffer.ReadString();
            // Debug.Log("服务器返回数据：" + data);
        }


        private static void ReceiveMessage()
        {
            while (true)
            {
                try

                {
                    //通过clientSocket接收数据
                    var receiveNumber = clientSocket.Receive(result);
                    // string strContent = Encoding.ASCII.GetString(result, 0, receiveNumber);
                    Debug.Log("服务器返回数据：" + receiveNumber);
                    // Debug.Log(receiveNumber);
                    // Console.WriteLine("接收服务端{0}消息{1}", clientSocket.RemoteEndPoint.ToString(),
                        // Encoding.ASCII.GetString(result, 0, receiveNumber));
                }
                catch (Exception ex)
                {
                    Debug.Log(ex.Message);
                    // Console.WriteLine(ex.Message);
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                    break;
                }
            }
        }


        /// <summary>
        /// 发送数据给服务器
        /// </summary>
        public void SendMessage(string data)
        {
            if (IsConnected == false)
                return;
            try
            {
                var buffer = new ByteBuffer();
                buffer.WriteString(data);
                clientSocket.Send(WriteMessage(buffer.ToBytes()));
            }
            catch
            {
                IsConnected = false;
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
        }

        /// <summary>
        /// 数据转换，网络发送需要两部分数据，一是数据长度，二是主体数据
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private static byte[] WriteMessage(byte[] message)
        {
            MemoryStream ms = null;
            using (ms = new MemoryStream())
            {
                ms.Position = 0;
                BinaryWriter writer = new BinaryWriter(ms);
                ushort msglen = (ushort) message.Length;
                writer.Write(msglen);
                writer.Write(message);
                writer.Flush();
                return ms.ToArray();
            }
        }
    }
}